﻿using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace IconPackEditor
{
    public partial class Application : Form
    {
        String FileName = null;

        Notepad_X.Main main = Notepad_X.Static.MainInstance;
        public Application()
        {
            InitializeComponent();
        }

        private void Application_Load(object sender, EventArgs e)
        {
            CreateNew(null, null);
            if (main.IconsCollection.Images.ContainsKey("icons"))
            {
                this.Icon = System.Drawing.Icon.FromHandle(new System.Drawing.Bitmap(main.IconsCollection.Images["icons"]).GetHicon());
            }else{
                this.ShowIcon = false;
            }
        }


        private void List_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (List.SelectedItems.Count < 0)
            {
                editGroup.Enabled = false;
            }
        }
        private void UpdateControlImages()
        {
            if (imageCollection.Images.ContainsKey("file"))
            {
                File_.Image = imageCollection.Images["file"];
            }
            else
            {
                File_.Image = null;
            }

            if (imageCollection.Images.ContainsKey("new"))
            {
                File_New.Image = imageCollection.Images["new"];
            }
            else
            {
                File_New.Image = null;
            }
            if (imageCollection.Images.ContainsKey("open"))
            {
                File_Open.Image = imageCollection.Images["open"];
            }
            else
            {
                File_Open.Image = null;
            }
            if (imageCollection.Images.ContainsKey("save"))
            {
                File_Save.Image = imageCollection.Images["save"];
            }
            else
            {
                File_Save.Image = null;
            }

            if (imageCollection.Images.ContainsKey("clear"))
            {
                btnClearImage.Image = imageCollection.Images["clear"];
                clearImageToolStrip.Image = imageCollection.Images["clear"];
            }
            else
            {
                btnClearImage.Image = null;
            }
            if (imageCollection.Images.ContainsKey("add"))
            {
                btnSetImage.Image = imageCollection.Images["add"];
                setImageToolStrip.Image = imageCollection.Images["add"];
            }
            else
            {
                btnSetImage.Image = null;
            }
        }
        private void btnSetImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog OpenImage = new OpenFileDialog();
            OpenImage.Filter = "Images|*.png;*.jpg;*.gif;*.bmp";
            OpenImage.Title = "Icon for " + List.SelectedItems[0].Text;
            if (OpenImage.ShowDialog() == DialogResult.OK)
            {
                String SelectedKey = List.SelectedItems[0].Text;
                if (imageCollection.Images.ContainsKey(SelectedKey))
                {
                    int index = imageCollection.Images.IndexOfKey(SelectedKey);
                    imageCollection.Images[index] = Image.FromFile(OpenImage.FileName);
                }else{
                    imageCollection.Images.Add(SelectedKey, Image.FromFile(OpenImage.FileName));
                }
                List.SelectedItems[0].ImageKey = SelectedKey;
                List.SelectedItems[0].SubItems[1].Text = System.IO.Path.GetFileNameWithoutExtension(OpenImage.FileName);
                List.SelectedItems[0].SubItems[2].Text = OpenImage.FileName;
                List.Update();
                List.Focus();
            }
            UpdateControlImages();
        }
        private void List_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                btnSetImage_Click(sender, null);
            }
        }

        private void btnClearImage_Click(object sender, EventArgs e)
        {
            String SelectedKey = List.SelectedItems[0].Text;

            List.SelectedItems[0].SubItems[1].Text = null;
            List.SelectedItems[0].SubItems[2].Text = null;
            List.SelectedItems[0].ImageKey = null;
            if (imageCollection.Images.ContainsKey(SelectedKey))
            {
                imageCollection.Images.RemoveByKey(SelectedKey);
            }
            
            //
            foreach (ListViewItem i in List.Items)
            {
                if (imageCollection.Images.ContainsKey(i.Text))
                {
                    i.ImageKey = i.Text;
                }else{
                    i.ImageKey = null;
                }
            }
            List.Update();
            List.Focus();
        }

        private void List_DoubleClick(object sender, EventArgs e)
        {
            if (List.SelectedItems.Count > 0)
            {
                btnSetImage_Click(null, null);
            }
        }
        private void SaveAs(String IconPackDirectory)
        {
            String IconPackName = info_Name.Text;
            String IconPackForlder = IconPackDirectory + "\\" + IconPackName ;

            XmlTextWriter xmlFile = new XmlTextWriter(IconPackForlder + ".xml", System.Text.Encoding.UTF8);

            if (!System.IO.Directory.Exists(IconPackForlder)){

                System.IO.Directory.CreateDirectory(IconPackForlder);
            }

            xmlFile.Formatting = Formatting.Indented;

            xmlFile.WriteStartElement("NotepadX");

            xmlFile.WriteStartElement("Information");

            xmlFile.WriteStartElement("Name");
            xmlFile.WriteString(info_Name.Text);
            xmlFile.WriteEndElement();

            xmlFile.WriteStartElement("Author");
            xmlFile.WriteString(info_Author.Text);
            xmlFile.WriteEndElement();

            xmlFile.WriteStartElement("Version");
            xmlFile.WriteString(info_Version.Text);
            xmlFile.WriteEndElement();

            xmlFile.WriteStartElement("Description");
            xmlFile.WriteString(info_Description.Text);
            xmlFile.WriteEndElement();

            xmlFile.WriteStartElement("Link");
            xmlFile.WriteString(info_Link.Text);
            xmlFile.WriteEndElement();

            xmlFile.WriteStartElement("ImageFolder");
            xmlFile.WriteString(info_Name.Text);
            xmlFile.WriteEndElement();

            xmlFile.WriteEndElement(); // Close Informations

            foreach (ListViewItem item in List.Items)
            {
                if (!String.IsNullOrEmpty(item.SubItems[2].Text))
                {
                    String ImageFileName = System.IO.Path.GetFileName(item.SubItems[2].Text);
                    if (item.SubItems[2].Text != IconPackForlder + "\\" + ImageFileName)
                    {
                        //MessageBox.Show(item.SubItems[2].Text + "\n\r" + IconPackForlder + "\\" + ImageFileName + "\n\r" + "Icon pack folder " + IconPackForlder + "\n\r" + "ImageFileName: " + ImageFileName); 
                        System.IO.File.Copy(item.SubItems[2].Text, IconPackForlder + "\\" + ImageFileName, true);

                    }else{

                    }
                    xmlFile.WriteStartElement("Icon");
                    xmlFile.WriteAttributeString("Key", item.Text);
                    xmlFile.WriteAttributeString("File", ImageFileName);

                    xmlFile.WriteEndElement();
                }
            }
            xmlFile.WriteEndElement(); // Close NotepadX
            xmlFile.Flush();
            xmlFile.Close();

            FileName = IconPackForlder + ".xml";
        }
        private void CreateNew(object sender, EventArgs e)
        {
            FileName = null;
            List.Items.Clear();
            imageCollection.Images.Clear();

            foreach (String name in Enum.GetNames(typeof(Notepad_X.Classes.Icons)))
            {
                if (name != "none")
                {
                    ListViewItem newItem = new ListViewItem(name);
                    newItem.Name = name;
                    newItem.SubItems.Add("");
                    newItem.SubItems.Add("");
                    newItem.ImageKey = name;
                    List.Items.Add(newItem);
                }
            }
            info_Name.Text = null;
            info_Author.Text = null;
            info_Description.Text = null;
            info_Version.Text = null;
            info_Link.Text = null;

            UpdateControlImages();
        }

        private void File_OpenClick(object sender, EventArgs e)
        {
            OpenFileDialog OpenIconPack = new OpenFileDialog();
            OpenIconPack.Filter = "Notepad X Icon Files (*.xml)|*.xml";
            OpenIconPack.InitialDirectory = Notepad_X.Main.System_ROOT + "\\Icons\\";
            OpenIconPack.Multiselect = false;
            if (OpenIconPack.ShowDialog() == DialogResult.OK)
            {
                OpenIcon(OpenIconPack.FileName);
                
            }
        }
        private void OpenIcon(String Path)
        {
            String[] Hash = Notepad_X.Classes.Settings.hashIconPack(Path);
            if (Hash == null)
            {
                MessageBox.Show("Error invalid icon file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                CreateNew(null, null);

                FileName = Path;

                info_Name.Text = Hash[0];
                info_Author.Text = Hash[1];
                info_Description.Text = Hash[3];
                info_Version.Text = Hash[2];
                info_Link.Text = Hash[4];

                String PackName = System.IO.Path.GetFileNameWithoutExtension(Path);
                String ImagesPath = System.IO.Path.GetDirectoryName(Path) + "\\" + PackName + "\\";

                XmlDocument xmlFile = new XmlDocument();
                xmlFile.Load(Path);


                foreach (XmlNode node in xmlFile.SelectNodes("NotepadX/Icon"))
                {
                    string key = node.Attributes.GetNamedItem("Key").InnerText.ToLower();
                    string file = node.Attributes.GetNamedItem("File").InnerText;
                    if (System.IO.File.Exists(ImagesPath + file))
                    {
                        if (List.Items.ContainsKey(key))
                        {
                            if (!imageCollection.Images.ContainsKey(key))
                            {
                                imageCollection.Images.Add(key, Image.FromFile(ImagesPath + file));
                                List.Items[key].ImageKey = key;
                                List.Items[key].SubItems[1].Text = System.IO.Path.GetFileNameWithoutExtension(ImagesPath + file);
                                List.Items[key].SubItems[2].Text = ImagesPath + file;
                            }
                        }
                    }
                }

                List.Update();
                List.Focus();
                FileName = Path;
                UpdateControlImages();
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Boolean ok = true;
            if (System.IO.File.Exists(Notepad_X.Main.System_ROOT + "\\Icons\\" + info_Name + ".xml"))
            {
                if (FileName != Notepad_X.Main.System_ROOT + "\\Icons\\" + info_Name.Text + ".xml")
                {

                    ok = false;
                    if (MessageBox.Show(info_Name + " iconpack alread exists do you want to replace it ?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        ok = true;
                    }
                    else
                    {

                    }
                }
            }
            if (ok)
            {
                SaveAs(Notepad_X.Main.System_ROOT + "\\Icons");
            }
        }

        private void exportAsPackpackFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog Dialog = new SaveFileDialog();
            Dialog.FileName = info_Name.Text;
            Dialog.Filter = "Pack Files (.pack)|*.pack";
            if (Dialog.ShowDialog() == DialogResult.OK)
            {

                Boolean ok = true;
                if(FileName != Notepad_X.Main.System_ROOT + "\\Icons\\" + info_Name.Text + ".xml"){
                    if (System.IO.File.Exists(Notepad_X.Main.System_ROOT + "\\Icons\\" + info_Name.Text + ".xml"))
                    {
                        ok = false;
                        if (MessageBox.Show(info_Name + " iconpack alread exists do you want to replace it ?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            ok = true;
                        }
                        else
                        {

                        }
                    }
                }
                if (ok)
                {
                    SaveAs(Notepad_X.Main.System_ROOT + "\\Icons");

                    Notepad_X.Classes.PackFileInfoCollection PackFileInfo = new Notepad_X.Classes.PackFileInfoCollection();
                    PackFileInfo.AddFile(Notepad_X.Main.System_ROOT + "\\Icons\\" + info_Name.Text + ".xml");
                    PackFileInfo.AddDirectory(Notepad_X.Main.System_ROOT + "\\Icons\\" + info_Name.Text, info_Name.Text + "\\");

                    Notepad_X.Classes.Packages.Pack(PackFileInfo, Dialog.FileName);
                }
            }
        }

        private void File_Import_Click(object sender, EventArgs e)
        {
            OpenFileDialog OpenFilePack = new OpenFileDialog();
            OpenFilePack.Filter = "PackFiles (*.pack)|*.pack";

            OpenFilePack.Multiselect = false;
            if (OpenFilePack.ShowDialog() == DialogResult.OK)
            {
                String PackName = System.IO.Path.GetFileNameWithoutExtension(OpenFilePack.FileName);

                if (Notepad_X.Classes.Packages.Unpack(OpenFilePack.FileName, Notepad_X.Main.System_ROOT + "\\Icons\\"))
                {
                    if (System.IO.File.Exists(Notepad_X.Main.System_ROOT + "\\Icons\\" + PackName + ".xml"))
                    {
                        OpenIcon(Notepad_X.Main.System_ROOT + "\\Icons\\" + PackName + ".xml");
                    }
                }
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

       
    }
}

